package xdu.lz.stage4_atomic.chapter4_atomicStampedReference_ABA;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * Created at 2019/10/16 0016 下午 11:57
 */
public class chapter3_atomicReferencePair_ABA {

    private static AtomicStampedReference<Integer> atomicRef
            = new AtomicStampedReference<>(100,0);

    public static void main(String[] args) {

        new Thread(()->{
            int stamp = atomicRef.getStamp();
            Integer value = atomicRef.getReference();
            System.out.println("currentStamp:"+stamp);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean success =
                    atomicRef.compareAndSet(value, value+1, stamp, stamp + 1);
            System.out.println(success);

        },"t1").start();
        new Thread(()->{

            Integer value = atomicRef.getReference();
            boolean success =
                    atomicRef.compareAndSet(value, value+1, atomicRef.getStamp(), atomicRef
                            .getStamp() + 1);

            System.out.println(success);
            value = atomicRef.getReference();
            success =
                    atomicRef.compareAndSet(value, value-1, atomicRef.getStamp(), atomicRef
                            .getStamp() + 1);
            System.out.println(success);
        },"t2").start();

    }
}
